﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using Light.Utility.Security;
using System.Drawing;

namespace Light.Utility
{
    /// <summary>
    /// Web请求辅助类
    /// </summary>
    public class WebHelper
    {

        #region Get、POST

        /// <summary>
        /// Post数据至目标url
        /// </summary>
        /// <param name="url">服务器URL</param>
        /// <param name="data">要发送的参数字符串</param>
        /// <param name="encoding"></param>
        /// <returns>服务器返回字符串</returns>
        public static string HttpPost(string url, string data, Encoding encoding)
        {
            byte[] postBytes = encoding.GetBytes(data);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=" + encoding.WebName;
            req.ContentLength = postBytes.Length;

            try
            {
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }

                using (WebResponse res = req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream(), encoding))
                    {
                        string strResult = sr.ReadToEnd();
                        return strResult;
                    }
                }

            }
            catch (WebException ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 从目标url，Get数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string HttpGet(string url, Encoding encoding)
        {
            string address = url;
            Uri uri = new Uri(address);
            WebRequest webReq = WebRequest.Create(uri);

            try
            {
                using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse())
                {
                    using (Stream respStream = webResp.GetResponseStream())
                    {
                        using (StreamReader objReader = new StreamReader(respStream, encoding))
                        {
                            string strRes = objReader.ReadToEnd();
                            return strRes;
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                return "无法连接到服务器/r/n错误信息：" + ex.Message;
            }
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Image HttpGet(string url)
        {
            string address = url;
            Uri uri = new Uri(address);
            WebRequest webReq = WebRequest.Create(uri);

            try
            {
                using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse())
                using (Stream respStream = webResp.GetResponseStream())
                {
                    Image image = Image.FromStream(respStream);
                    return image;
                }
            }
            catch (WebException ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion

        #region Cookies

        /// <summary>
        /// 设置客户端cookie（有效期一年）
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCookie(string key, string value)
        {
            SetCookie(key, value, 30);
        }

        /// <summary>
        /// 设置客户端cookie（有效期一个月）
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCookie(string key, object value)
        {
            SetCookie(key, value, 30);
        }

        /// <summary>
        /// 设置客户端Cookie
        /// </summary>
        /// <param name="key">cookie名称</param>
        /// <param name="value">cookie值</param>
        /// <param name="expireDays"></param>
        public static void SetCookie(string key, object value, double expireDays)
        {
            try
            {
                string str = string.Empty;
                if (value != null && !String.IsNullOrEmpty(value.ToString()))
                {
                    str = Light.Utility.Security.Base64StringCryptor.Encrypt(value.ToString(), "aeogep");
                }
                HttpCookie cookie = new HttpCookie(key, str);
                cookie.Expires = DateTime.Now.AddDays(expireDays);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch
            {

            }
        }

        /// <summary>
        /// 取出Cookie
        /// </summary>
        /// <param name="key">cookie名称</param>
        /// <returns></returns>
        public static string GetCookie(string key)
        {
            string value = string.Empty;

            string cipher = HttpContext.Current.Request.Cookies[key] != null ? HttpContext.Current.Request.Cookies[key].Value : string.Empty;
            if (!String.IsNullOrEmpty(cipher))
            {
                value = Light.Utility.Security.Base64StringCryptor.Decrypt(cipher, "aeogep");
            }
            return value;
        }


        public static string GetCookie(string key, string defaultValue)
        {
            string value = GetCookie(key);
            if (String.IsNullOrEmpty(value))
                value = defaultValue;
            return value;
        }

        public static int GetCookie(string key, int defalutValue)
        {
            int result = defalutValue;

            string value = GetCookie(key);
            if (!String.IsNullOrEmpty(value))
                result = StringHelper.ToInt(value);

            return result;
        }

        public static decimal GetCookie(string key, decimal defalutValue)
        {
            decimal result = defalutValue;

            string value = GetCookie(key);
            if (!String.IsNullOrEmpty(value))
                result = StringHelper.ToDecimal(value);

            return result;
        }

        public static bool GetCookie(string key, bool defalutValue)
        {
            bool result = defalutValue;

            string value = GetCookie(key);
            if (!String.IsNullOrEmpty(value))
                result = Boolean.Parse(value);

            return result;
        }

        #endregion


        public static object GetCache(string name)
        {
            try
            {
                return System.Web.HttpContext.Current.Cache[name];
            }
            catch (Exception ex)
            {
                TextHelper.Console("error.log", "GetCache " + name + " 发生错误，" + ex.Message, true);
                return null;
            }
        }


        public static void SetCache(string name, object value)
        {
            try
            {
                System.Web.HttpContext.Current.Cache[name] = value;
            }
            catch (Exception ex)
            {
                TextHelper.Console("error.log", "SetCache " + name + " 发生错误，" + ex.Message, true);
            }
        }

        #region Session

        public static void SetSession(string name, object value)
        {
            SetSession(name, value, 60);
        }

        /// <summary>
        /// 设置session
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="effectiveMinutes">有效分钟</param>
        public static void SetSession(string name, object value, int effectiveMinutes)
        {
            if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Session != null)
            {
                System.Web.HttpContext.Current.Session[name] = value;
                System.Web.HttpContext.Current.Session.Timeout = effectiveMinutes;
            }
        }

        public static string GetSession(string name)
        {
            if (System.Web.HttpContext.Current != null)
                return System.Web.HttpContext.Current.Session[name] as String;
            else
                return string.Empty;
        }

        public static string GetSession(string name, string defaultValue)
        {
            string value = GetSession(name);
            if (String.IsNullOrEmpty(value))
                value = defaultValue;
            return value;
        }

        public static T GetSession<T>(string name)
        {
            T result = default(T);

            try
            {
                if (System.Web.HttpContext.Current != null)
                    result = (T)System.Web.HttpContext.Current.Session[name];
            }
            catch
            {
                result = default(T);
            }

            return result;

        }

        public static T GetSession<T>(string name, T defaultValue)
        {
            T value = GetSession<T>(name);
            if (value == null || value.Equals(default(T)))
                value = defaultValue;
            return value;
        }

        #endregion

        #region 获取IP地址归属地信息

        /// <summary>
        /// 获取当前请求来源IP归属地信息
        /// </summary>
        /// <returns></returns>
        public static string GetBelongsInfo()
        {
            return GetBelongsInfo(HttpContext.Current.Request.UserHostAddress);
        }

        /// <summary>
        /// 获取IP地址归属地
        /// </summary>
        /// <param name="strIPAddress"></param>
        /// <returns>例：广东省深圳市 移动</returns>
        public static string GetBelongsInfo(string strIPAddress)
        {
            string s = WebHelper.HttpGet("http://www.ip138.com/ips1388.asp?ip=" + strIPAddress + "&action=2", Encoding.GetEncoding("gb2312"));

            int a = s.IndexOf("本站主数据：") + "本站主数据：".Length;
            int b = s.IndexOf("参考数据一");

            if ((b - a) > 0)
            {
                return s.Substring(a, b - a).Replace("</li><li>", "");
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取当前请求来源IP地址所在城市
        /// </summary>
        /// <returns></returns>
        public static string GetBelongsCity()
        {
            return GetBelongsCity(HttpContext.Current.Request.UserHostAddress);
        }

        /// <summary>
        /// 获取IP地址所在城市
        /// </summary>
        /// <param name="strIPAddress"></param>
        /// <returns></returns>
        public static string GetBelongsCity(string strIPAddress)
        {
            string city = string.Empty;


            string info = GetBelongsInfo(strIPAddress);
            int a = info.IndexOf("省") + 1;
            int b = info.IndexOf("市");
            if ((b - a) > 0)
            {
                city = info.Substring(a, b - a);
            }
            return city;
        }

        /// <summary>
        /// 获取当前请求来源IP地址所在省份
        /// </summary>
        /// <returns></returns>
        public static string GetBelongsProvince()
        {
            return GetBelongsProvince(HttpContext.Current.Request.UserHostAddress);
        }

        /// <summary>
        /// 获取IP地址所在省份
        /// </summary>
        /// <param name="strIPAddress"></param>
        /// <returns></returns>
        public static string GetBelongsProvince(string strIPAddress)
        {
            string city = string.Empty;


            string info = GetBelongsInfo(strIPAddress);
            int a = info.IndexOf("省") + 1;
            if (a > 0)//省份
            {
                city = info.Substring(0, a);
            }
            else//直辖市
            {
                a = info.IndexOf("市") + 1;
                if (a > 0)
                {
                    city = info.Substring(0, a);
                }
                else
                {
                    a = info.IndexOf("自治") + 1;
                    city = info.Substring(0, a);
                }
            }
            return city;
        }

        public static string GetCurrentRequestIP()
        {
            if (HttpContext.Current == null)
                return null;
            else
                return HttpContext.Current.Request.UserHostAddress;
        }

        #endregion


        /// <summary>
        /// 是否通过QueryString发送请求
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool IsQuery(string name)
        {
            if (HttpContext.Current == null)
                return false;
            else
                return !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[name]);
        }


        public static bool IsRequest(string name)
        {
            if (HttpContext.Current == null)
                return false;
            else
                return !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[name])
                    || !String.IsNullOrEmpty(HttpContext.Current.Request.Form[name]);
        }

        public static bool IsRequest(string key, string value)
        {
            bool has = String.Compare(HttpContext.Current.Request.QueryString[key], value, true) == 0;
            if (!has)
            {
                has = String.Compare(HttpContext.Current.Request.Form[key], value, true) == 0;
            }
            return has;
        }

        /// <summary>
        /// 优先取 Form 数据，再取 QueryString
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string Request(string name)
        {
            if (HttpContext.Current == null)
                return null;

            //Request[name] 取数据的顺序：QueryString,Form,ServerVariables
            string str = HttpContext.Current.Request.Form[name];
            if (String.IsNullOrEmpty(str))
            {
                str = HttpContext.Current.Request.QueryString[name];
            }
            return str;
        }

        /// <summary>
        /// 获取请求的数据Form,QueryString
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int GetRequest(string name, int defaultValue)
        {
            int result = defaultValue;

            string value = Request(name);
            if (!String.IsNullOrEmpty(value) && StringHelper.IsNumeric(value))
                result = StringHelper.ToInt(value);

            return result;
        }

        public static decimal GetRequest(string name, decimal defaultValue)
        {
            decimal result = defaultValue;

            string value = Request(name);
            if (!String.IsNullOrEmpty(value) && StringHelper.IsNumeric(value))
                result = StringHelper.ToDecimal(value);

            return result;
        }

        public static string GetRequest(string name, string defaultValue)
        {
            string result = defaultValue;

            string value = Request(name);
            if (!String.IsNullOrEmpty(value))
                result = value;
            return result;
        }

        public static DateTime GetRequest(string name, DateTime defaultValue)
        {
            DateTime result = defaultValue;

            string value = Request(name);
            if (!DateTime.TryParse(Request(name), out result))
            {
                result = defaultValue;
            }
            return result;
        }

        public static bool GetRequest(string name, bool defaultValue)
        {
            bool result = defaultValue;

            string value = Request(name);
            if (!Boolean.TryParse(Request(name), out result))
            {
                result = defaultValue;
            }
            return result;
        }


        /// <summary>
        /// 获取客户端发送的id数据 Form,QueryString
        /// </summary>
        /// <returns></returns>
        public static string GetRequestID()
        {
            return GetRequest("id", string.Empty);
        }

        /// <summary>
        /// 获取客户端发送的id数据 Form,QueryString
        /// </summary>
        /// <returns></returns>
        public static int GetRequestID(string name)
        {
            return GetRequest(name, -1);
        }

        /// <summary>
        /// 获取客户端发送的ids数据
        /// 格式为：ids=32,33,35
        /// </summary>
        /// <returns></returns>
        public static IList<int> GetRequestIDs()
        {
            return GetRequestIDs("ids", ',');
        }

        /// <summary>
        /// 获取客户端发送的IDs数据
        /// 格式为：name=32分隔符33分隔符35
        /// </summary>
        /// <param name="name">请求name</param>
        /// <param name="splitChar">ids分隔符</param>
        /// <returns></returns>
        public static IList<int> GetRequestIDs(string name, char splitChar)
        {
            string idsString = WebHelper.Request(name);
            return StringHelper.ToIntList(idsString, splitChar);
        }

        /// <summary>
        /// Http当前上下文
        /// </summary>
        public static HttpContext CurContext
        {
            get
            {
                return HttpContext.Current;
            }
        }


        /// <summary>
        /// aspx页面静态化
        /// </summary>
        /// <param name="aspxUrl"></param>
        /// <param name="staticUrl"></param>
        /// <param name="encoding"></param>
        public static void StaticPage(string aspxUrl, string staticUrl, Encoding encoding)
        {
            try
            {
                System.IO.StringWriter swHtml = new System.IO.StringWriter();
                HttpContext.Current.Server.Execute(aspxUrl, swHtml);
                string contentStr = swHtml.ToString();

                System.IO.StreamWriter sWriter = new System.IO.StreamWriter(staticUrl, false, encoding);
                sWriter.Write(contentStr);
                sWriter.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("页面静态化 Light.Utility.WebHelper.StaticPage 失败:" + ex.Message);
            }

        }

        private const string COOKIE_NAME_TOKEN_IDENTITY = "light_utility_identity_id";

        /// <summary>
        /// 获取当前请求生成一个令牌
        /// </summary>
        /// <param name="identityId">唯一标识</param>
        /// <returns></returns>
        public static string SetAccessToken(object identityId)
        {

            WebHelper.SetCookie(COOKIE_NAME_TOKEN_IDENTITY, identityId);

            string data = CurContext.Request.UserAgent + "※" + CurContext.Request.UserHostAddress + "※" + DateTime.Now.ToString("yyyyMMdd") + CurContext.Request.UserHostName + identityId;
            return Serializer.CreateMD5(data).Replace("-", "").ToLower();

        }

        public static string GetAccessToken()
        {
            string identityId = WebHelper.GetCookie(COOKIE_NAME_TOKEN_IDENTITY);

            string data = CurContext.Request.UserAgent + "※" + CurContext.Request.UserHostAddress + "※" + DateTime.Now.ToString("yyyyMMdd") + CurContext.Request.UserHostName + identityId;
            return Serializer.CreateMD5(data).Replace("-", "").ToLower();
        }

        /// <summary>
        /// 验证令牌是否合法
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool ValidateAccessToken(string token)
        {


            string newToken = WebHelper.GetAccessToken();
            return newToken == token;
        }


        /// <summary>
        /// 从当前请求中获取客户端Post数据
        /// </summary>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetPostData(Encoding encoding)
        {
            Stream stream = WebHelper.CurContext.Request.InputStream;
            byte[] b = new byte[stream.Length];
            stream.Read(b, 0, (int)stream.Length);
            return encoding.GetString(b);
        }

        /// <summary>
        /// 是否为Post请求
        /// </summary>
        public static bool IsPostRequest
        {
            get
            {
                return WebHelper.CurContext.Request.HttpMethod.ToLower() == "post";
            }
        }

        /// <summary>
        /// 获取表单的数据
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> GetFormDatas()
        {
            Dictionary<string, object> values = new Dictionary<string, object>();

            foreach (string key in HttpContext.Current.Request.Form.Keys)
            {
                string value = HttpContext.Current.Request.Form[key];
                object obj = value;

                if (value.ToLower() == "true")
                    obj = true;
                else if (value.ToLower() == "false")
                    obj = false;

                if (values.Keys.Contains(key))
                    values[key] = obj;
                else
                    values.Add(key, obj);
            }
            return values;
        }

        /// <summary>
        /// 获取URL中的数据
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> GetQueryStringDatas()
        {
            Dictionary<string, object> values = new Dictionary<string, object>();

            foreach (string key in HttpContext.Current.Request.QueryString.AllKeys)
            {
                string value = HttpContext.Current.Request.QueryString[key];
                object obj = value;

                if (value.ToLower() == "true")
                    obj = true;
                else if (value.ToLower() == "false")
                    obj = false;

                if (values.Keys.Contains(key))
                    values[key] = obj;
                else
                    values.Add(key, obj);
            }

            return values;
        }

        /// <summary>
        /// 是否为Get请求
        /// </summary>
        public static bool IsGetRequest
        {
            get
            {
                return WebHelper.CurContext.Request.HttpMethod.ToLower() == "get";
            }
        }

        //获取客户端设备信息
        public static string GetDevice()
        {
            try
            {
                string userAgent = WebHelper.CurContext.Request.UserAgent.ToLower();

                if (userAgent.IndexOf("android") > -1)
                    return "Android";
                else if (userAgent.IndexOf("iphone") > -1)
                    return "iPhone";
                else if (userAgent.IndexOf("ipad") > -1)
                    return "iPad";
                else
                    return "PC";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 是否是移动端访问（.ashx）
        /// </summary>
        /// <returns></returns>
        public static bool IsMobileDevice()
        {
            //string device = GetDevice();
            //return device != "PC";

            return WebHelper.CurContext.Request.RawUrl.IndexOf(".ashx") > -1;
        }

        /// <summary>
        /// URL字符编码
        /// </summary>
        public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpContext.Current.Server.UrlEncode(str);
        }

        /// <summary>
        /// URL字符解码
        /// </summary>
        public static string UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }

        /// <summary>
        /// 清空内容中的HTML标签
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public static string ClearHTML(string htmlContent)//将HTML去除
        {
            #region
            //删除脚本

            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"<script[^>]*?>.*?</script>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //删除HTML
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"<(.[^>]*)>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"([\r\n])[\s]+", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"-->", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"<!--.*", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //Htmlstring =System.Text.RegularExpressions. Regex.Replace(Htmlstring,@"<A>.*</A>","");
            //Htmlstring =System.Text.RegularExpressions. Regex.Replace(Htmlstring,@"<[a-zA-Z]*=\.[a-zA-Z]*\?[a-zA-Z]+=\d&\w=%[a-zA-Z]*|[A-Z0-9]","");
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(quot|#34);", "\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(amp|#38);", "&", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(lt|#60);", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(gt|#62);", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(nbsp|#160);", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(iexcl|#161);", "\xa1", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(cent|#162);", "\xa2", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(pound|#163);", "\xa3", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&(copy|#169);", "\xa9", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, @"&#(\d+);", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            htmlContent.Replace("<", "");
            htmlContent.Replace(">", "");
            htmlContent.Replace("\r\n", "");
            //Htmlstring=HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            #endregion

            return htmlContent;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath">源文件的完整物理路径</param>
        /// <param name="outputFileName">文件名称，无需扩展名，为空则与源文件名一致</param>
        public static void DownloadFile(string filePath, string outputFileName)
        {
            if (File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                WebHelper.CurContext.Response.Clear();
                WebHelper.CurContext.Response.ClearHeaders();
                WebHelper.CurContext.Response.Buffer = false;

                string mimeType = string.Empty;
                switch (file.Extension.ToLower())
                {
                    case ".png":
                    case ".jpg":
                    case ".gif":
                    case ".jpeg":
                        mimeType = "application/octet-stream";
                        break;
                    case ".mp4":
                        mimeType = "video/mpeg4";
                        break;
                    case ".avi":
                        mimeType = "video/avi";
                        break;
                    case ".exe":
                        mimeType = "	application/x-msdownload";
                        break;
                    case ".txt":
                        mimeType = "text/plain";
                        break;
                    case ".xls":
                    case ".xlsx":
                        mimeType = "application/vnd.ms-excel";
                        break;
                    case ".ppt":
                    case ".pptx":
                        mimeType = "	application/vnd.ms-powerpoint";
                        break;
                    case ".pdf":
                        mimeType = "	application/pdf";
                        break;
                    case ".doc":
                    case ".docx":
                        mimeType = "application/msword";
                        break;
                    case ".apk":
                        mimeType = "application/vnd.android.package-archive";
                        break;
                }
                WebHelper.CurContext.Response.ContentType = mimeType;
                WebHelper.CurContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(!String.IsNullOrEmpty(outputFileName) ? (outputFileName + file.Extension) : file.Name, System.Text.Encoding.UTF8));
                WebHelper.CurContext.Response.AppendHeader("Content-Length", file.Length.ToString());
                WebHelper.CurContext.Response.WriteFile(file.FullName);
                WebHelper.CurContext.Response.Flush();
                WebHelper.CurContext.Response.End();
            }
        }


        /// <summary>
        /// 获取当前请求的URL
        /// post请求参数会拼接成queryString
        /// </summary>
        /// <returns></returns>
        public static string GetRequestUrl()
        {
            try
            {
                string url = CurContext.Request.Url.ToString();
                string formString = string.Empty;

                var keys = CurContext.Request.Form.Keys;
                if (keys.Count > 0)
                {
                    formString = url.Contains("?") ? "&" : "?";
                }
                foreach (var key in keys)
                {
                    formString += key + "=" + CurContext.Request.Form[key.ToString()] + "&";
                }

                if (!String.IsNullOrEmpty(formString))
                {
                    formString += "type=post";
                }

                return url + formString;

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 为请求的指定字符串每分钟生成一唯一的MD5
        /// </summary>
        /// <param name="identityId"></param>
        /// <returns></returns>
        public static string GetIdentityKey(string identityId)
        {
            string data = "identity_key_" + CurContext.Request.UserAgent + "※" + CurContext.Request.UserHostAddress + "※" + DateTime.Now.ToString("yyyyMMddHHmm") + CurContext.Request.UserHostName + identityId;
            return Serializer.CreateMD5(data);
        }


        /// <summary>
        /// 获取站点根目录
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            return HttpContext.Current.Server.MapPath("./");
        }
    }
}
